package com.css.sword.knowing.search.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import com.css.sword.knowing.search.HighLightField;
import com.css.sword.knowing.search.OrderField;
import com.css.sword.knowing.search.SearchField;
import com.css.sword.knowing.search.SearchInput;
import com.css.sword.knowing.search.SearchResult;
import com.css.sword.knowing.search.Searcher;
import com.css.sword.knowing.search.comm.SearchConst;
import com.css.sword.knowing.search.exception.ArgException;

/**
 * @author 作者 E-mail:caihx@css.com.cn
 * @date 创建时间：2017年1月9日 下午12:59:16
 * @version 1.0
 */
public class TermBoost {

    private String indexName = "";
    private String[] typeName = {};

    private String[] keywords = {};

    private int pagesize = 10;
    private int pageno = 1;

    public String getIndexName() {
        return indexName;
    }

    public void setIndexName(String indexName) {
        this.indexName = indexName;
    }

    public String[] getTypeName() {
        return typeName;
    }

    public void setTypeName(String[] typeName) {
        this.typeName = typeName;
    }

    public String[] getKeywords() {
        return keywords;
    }

    public void setKeywords(String[] keywords) {
        this.keywords = keywords;
    }

    public int getPagesize() {
        return pagesize;
    }

    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }

    public int getPageno() {
        return pageno;
    }

    public void setPageno(int pageno) {
        this.pageno = pageno;
    }

    public String rss2Json(List<SearchResult> rss) throws IOException {
        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        for (SearchResult rs : rss) {
            long count = rs.getTotalNum();
            long pagenum = (long) Math.ceil((double) count / pagesize);

            jsonBuilder.startObject();

            jsonBuilder.field("count", rs.getTotalNum());
            jsonBuilder.field("total", rs.getTotalNum());
            jsonBuilder.field("pagenum", pagenum);

            jsonBuilder.startArray("docs");
            List<Map> data = rs.getData();
            String key = null;
            Object value = null;
            for (Map<String, String> fields : data) {
                jsonBuilder.startObject();
                Iterator<String> it = fields.keySet().iterator();
                while (it.hasNext()) {
                    key = it.next();
                    value = fields.get(key);

                    if ("_id".equalsIgnoreCase(key) || "_type".equalsIgnoreCase(key))
                        continue;

                    jsonBuilder.field(key, value);

                    System.out.println(key + ":" + value);
                }
                jsonBuilder.endObject();
                System.out.println("++++++++++++++++++rs++++++++++++++++++++");
            }
            jsonBuilder.endArray();

            break;
        }

        jsonBuilder.endObject();

        String jsonString = jsonBuilder.string();

        return jsonString;
    }

    public String getSearch() throws IOException, ElasticsearchException, ArgException {

        XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();

        return indexSearch();
    }

    public String indexSearch() throws ArgException, IOException {
        String jsonString = "";

        SearchInput si = new SearchInput();
        si.setIndexName(indexName);
        si.setTypeNames(typeName);

        ArrayList<SearchField> where = new ArrayList<SearchField>();

        for (int i = 0; i < keywords.length; i++) {
            SearchField f = new SearchField();
            f.setField("tags");
            f.setMethod(SearchConst.SEARCH_METHOD_TERM);
            f.setOperator(SearchConst.SEARCH_OPERATOR_SHOULD);
            String[] temp = keywords[i].split(":");
            String term = "";
            float weight = 0.0f;

            term = temp[0];
            if (temp.length > 1) {
                weight = Float.valueOf(temp[1]);
                f.setBoost(weight);
            }
            f.setSearchValue(term);

            where.add(f);
            // f.setConstantScoreQuery(true);
        }

        si.setSearchFields(where);
        si.setReturnFields(new String[] { "tags", "title" });

        si.setSystemID("public");
        si.setFrom((pageno - 1) * pagesize);
        si.setSize(pagesize);

        List<SearchInput> sis = new ArrayList<SearchInput>();
        sis.add(si);

        Searcher.Debug = true;
        List<SearchResult> rss = Searcher.multiIndexSearch(sis);

        jsonString = rss2Json(rss);

        return jsonString;
    }

    public static void main(String[] args) {

        TermBoost s = new TermBoost();

        s.setIndexName("test_term");
        s.setTypeName(new String[] {});
        s.setKeywords(new String[] {"彩礼", "公示催告:3", "聘财" });

        s.setPagesize(5);
        s.setPageno(1);

        try {
            String ret = s.getSearch();
        } catch (IOException | ArgException e) {
            // TODO Auto-generated catch block
            System.out.println("aaaaaa");
            e.printStackTrace();
        }

        // System.out.println("++++++++++++++++++json++++++++++++++++++++");
        // System.out.println(ret);
        /*
         * String detail = s.getDetail("artistnews", "news",
         * "eb05fd04-224e-4d01-a595-f473f146219c");
         * System.out.println("++++++++++++++++++detail++++++++++++++++++++");
         * System.out.println(detail);
         */

        // s.agg();

        // Searcher.terms("artistnews", "news");
        // Searcher.b();
    }
}
